local xundao = fk.CreateSkill {
  name = "xundao",
}
U = require "packages/utility/utility"
xundao:addEffect(fk.AskForRetrial, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      table.find(player.room.alive_players, function(p)
        return not p:isNude()
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room.alive_players, function(p) return not p:isNude() end)
    local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 2, "#xundao-choose", self.name, true)
    if #tos > 0 then
      event:setCostData(self,tos)
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:sortPlayersByAction(event:getCostData(self))
    local ids = {}
    for _, id in ipairs(event:getCostData(self)) do
      local p = room:getPlayerById(id)
      if not p.dead and not p:isNude() then
        local card = room:askForDiscard(p, 1, 1, true, self.name, false, ".", "#xundao-discard:"..player.id)
        table.insertIfNeed(ids, card[1])
      end
    end
    if player.dead then return end
    ids = table.filter(ids, function (id)
      return table.contains(room.discard_pile, id)
    end)
    if #ids == 0 then return end
    local cards = U.askforChooseCardsAndChoice(player, ids, {"OK"}, self.name, "#xundao-retrial")
    room:retrial(Fk:getCardById(cards[1]), player, data, self.name)
  end,
})

return xundao